package com.zige.zige.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.blueware.agent.android.BlueWare;
import com.google.gson.Gson;
import com.sina.weibo.sdk.utils.MD5;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zige.zige.LittleZebraApplication;
import com.zige.zige.R;
import com.zige.zige.bean.HomeBean;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.jpush.utils.ExampleUtil;
import com.zige.zige.pojo.UserInfo;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.ACache;
import com.zige.zige.utils.SharedPreferencesUtils;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.utils.ToastUtils;
import com.zige.zige.utils.cacheimage.AsyncImageLoader;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by Fei on 2015/11/4.
 * 初始页面
 */
public class WelcomeActivity extends BaseActivity {
    private Activity activity;
    private int mCode=0;
    private View rootView;

    private HomeBean mHomeBean;

    private UserInfo userInfo;
    private String loginAccount;
    private String loginPassword;
    private ACache mCache;
    private String mUrlKey,openVoiceUrl;

    private Handler mHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            StartGuidePager();
        }
    };

    private Thread downLoadThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏2222222222
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_welcome);
        mCache = ACache.get(this);
        activity = this;


        JPushInterface.init(getApplication());

        BlueWare.withApplicationToken("94A116DA16208486A0D7DC46AC6E214700").start(this.getApplication());
        sendRequest();
        initView();
        isGetUserInfo();
        registerMessageReceiver();  // used for receive msg

    }


    private void initView(){
        rootView = findViewById(R.id.welcome);
    }

    private void sendRequest() {
        final String appVersion = SystemUtils.getVersionName(this).trim();
        String platformType = "android";
        String loginType = "0";
        String devicedId = SystemUtils.getDeviceKey(this).trim();
        String pushKey = JPushInterface.getRegistrationID(this);

        userInfo = application.getUserInfo();
        if (application.isLogin()) {
            loginAccount = userInfo.phoneNumber;
            loginPassword = userInfo.userPassword;
        }else{
            loginAccount = null;
            loginPassword = null;
        }
        mUrlKey = getOpenClientUrl(appVersion,platformType,loginType,loginAccount,loginPassword,devicedId,pushKey);
        class homeCallBack extends Callback<HomeBean> {
            @Override
            public void onBefore(Request request) {
                super.onBefore(request);
            }

            @Override
            public HomeBean parseNetworkResponse(Response response) throws IOException {
                String string = response.body().string();
                HomeBean homeBean = new Gson().fromJson(string, HomeBean.class);
                mCache.put(mUrlKey,string);
                return homeBean;
            }

            @Override
            public void onError(Request request, Exception e) {
            }

            @Override
            public void onResponse(HomeBean response) {
                mHomeBean = response;
                LittleZebraApplication.getInstance().setHomeBean(mHomeBean);
                if(mHomeBean.getCode().equals("0000")){
                    if(mHomeBean.getOpenClientVoice()!=null){
                        SharedPreferencesUtils.saveValue(WelcomeActivity.this,"voiceUrl",mHomeBean.getOpenClientVoice());
                    }
                    if(mHomeBean.getShowCommentAlert()!=null){
                        SharedPreferencesUtils.saveValue(WelcomeActivity.this,"showCommentAlert",mHomeBean.getShowCommentAlert());
                    }

                    if(mHomeBean.getOpenClientImg() != null){
                        final String urlKey = mCache.getAsString("OpenClientImage");
                        if(urlKey == null || !urlKey.equals(MD5.hexdigest(mHomeBean.getOpenClientImg()))){
                            AsyncImageLoader imageLoader =new AsyncImageLoader(WelcomeActivity.this);
                            imageLoader.downloadImage(mHomeBean.getOpenClientImg(),new AsyncImageLoader.ImageCallback(){
                                public void onImageLoaded(Bitmap bitmap, String imageUrl){
                                    if(bitmap != null){
                                        mCache.put(MD5.hexdigest(imageUrl), bitmap);
                                        mCache.put("OpenClientImage",MD5.hexdigest(imageUrl));
                                    }
                                }
                            });
                        }
                    }

                }

            }

            @Override
            public void onAfter() {
                super.onAfter();
                mHandler.sendEmptyMessageDelayed(1,2000);  //2秒后关闭该页面
                // StartGuidePager();
            }
        }

        OkHttpUtils.post().url(UrlConsts.APP_POWERED_UP)
                .addParams("version", appVersion)
                .addParams("platform", platformType)
                .addParams("loginType", loginType)
                .addParams("account", loginAccount == null ? "" : loginAccount)
                .addParams("password", loginPassword == null ? "" : loginPassword)
                .addParams("deviceId", devicedId)
                .addParams("pushKey", pushKey)
                .addParams("hisFirst", "1")
                .addParams("dayFirst", "1")
                .build().connTimeOut(3000)
                .execute(new homeCallBack());
    }

    private String openPicture;
    private void openSendRequest(){
        final String appVersion = SystemUtils.getVersionName(WelcomeActivity.this).trim();
        String platformType = "android";
        String loginType = "0";
        String devicedId = SystemUtils.getDeviceKey(WelcomeActivity.this).trim();
        String pushKey = JPushInterface.getRegistrationID(WelcomeActivity.this);
        HashMap<String, String> params = new HashMap<>();
        params.put("version", appVersion);
        params.put("platform", platformType);
        params.put("loginType", loginType);
        params.put("account", loginAccount == null ? "" : loginAccount);
        params.put("password", loginPassword == null ? "" : loginPassword);
        params.put("deviceId", devicedId);
        params.put("pushKey", pushKey);
        params.put("hisFirst", String.valueOf(1));
        params.put("dayFirst", String.valueOf(1));
        TaskExecutor.getInstance().execute(new PostRequestTask(params, WelcomeActivity.this, UrlConsts.APP_POWERED_UP) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    String msg = object.getString("message");
                    if(code==0){
                        openPicture = object.getString("openClientImg");
                    }else {
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    ToastUtils.showToast(context, e.getMessage());
                } finally {
//                    closeLoadingDialog();
                }
            }
        });

    }

    private String getOpenClientUrl(String version,String platform,String loginType,String account,String password,String deviceId,String pushKey){
        StringBuffer sb =new StringBuffer(UrlConsts.APP_POWERED_UP);
        sb.append("?version=").append(version).append("&platform=").append(platform).append("&loginType=").append(loginType)
                .append("&account=").append(account == null ? "" : loginAccount).append("&password=").append(password == null ? "" : password)
                .append("&deviceId=").append(deviceId).append("&pushKey=").append(pushKey);
        return MD5.hexdigest(sb.toString());
    }




    private void StartGuidePager() {
        // Intent intent1 = new Intent(this,HomeActivity.class);
        Bundle bundle =new Bundle();
        bundle.putString("urlkey",mUrlKey);
        Intent intent = new Intent(this, Welcome2Activity.class);
        intent.putExtras(bundle);
        startActivity(intent);

        finish();
        overridePendingTransition(R.anim.welocom_in, R.anim.welcom_out);
    }



    private void isGetUserInfo(){
        boolean isLogin = (boolean) SharedPreferencesUtils.getValue(this, SharedPreferencesUtils.keep_login_state, false);
        String phone=(String)SharedPreferencesUtils.getValue(this, SharedPreferencesUtils.keep_login_userCount, "");
        String password =(String)SharedPreferencesUtils.getValue(this, SharedPreferencesUtils.keep_login_password, "");
        if(isLogin){
            userLogin(phone,password);
        }else {
            return;
        }
    }



    /**
     * loginType 0 登录类型
     * account  账号(手机号/qq/微信)
     * password 用户密码
     * deviceId 设备id
     * pushKey 极光推送key
     */

    private void userLogin(String phone,String password) {
        String type = "0";

        String deviceId = SystemUtils.getDeviceKey(activity).trim();
        String pushKey = JPushInterface.getRegistrationID(getApplicationContext());
        HashMap<String, String> parms = new HashMap<String, String>();
        parms.put("loginType", type);
        parms.put("account", phone);
        parms.put("password", password);
        parms.put("deviceId", deviceId);
        parms.put("pushKey", pushKey);

        TaskExecutor.getInstance().execute(new PostRequestTask(parms, activity, UrlConsts.USER_LOGIN) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    mCode = code;
                    String msg = object.getString("message");
                    closeLoadingDialog();
                    if (code == 0000) {
                        UserInfo userInfo = new UserInfo();
                        userInfo.parsefromJSON(object.getString("userInfo"));
                        application.setUserInfo(userInfo);
                        new Handler() {
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                            }
                        }.sendEmptyMessageDelayed(1, 500);

                    } else {
//                        closeLoadingDialog();
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    ToastUtils.showToast(activity, e.getMessage());
                } finally {
                }
            }
        });

    }

    public static boolean isForeground = false;

    @Override
    protected void onResume() {
        isForeground = true;
        JPushInterface.onResume(activity);
        super.onResume();
    }

    @Override
    protected void onPause() {
        isForeground = false;
        JPushInterface.onPause(activity);
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }



    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!ExampleUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
            }
        }
    }


}